from global_param import _global_dict
from win32com.client import Dispatch  # pip install pypiwin32
import normal
import xlwings as xw
import os
import zipfile


# table_nums = doc.Tables.Count
# print(table_nums)


def insert_pic(doc_pointer, table, path):
    pic_height = 255
    for i in range(1, 4):
        real_path = path + str(i) + '.jpg'
        pic_res = doc_pointer.Tables[table].Cell(3, i).Range.InlineShapes.AddPicture(real_path)
        # pic_res.LockAspectRatio = -1  # 锁定原图宽高比
        origin_h = pic_res.Height
        origin_w = pic_res.Width
        pic_res.Height = pic_height
        pic_res.Width = int((pic_height / origin_h) * origin_w)
        if i != 3:
            real_path = path + str(i + 3) + '.jpg'
            pic_res = doc_pointer.Tables[table].Cell(4, i).Range.InlineShapes.AddPicture(real_path)
            # pic_res.LockAspectRatio = -1  # 锁定原图宽高比
            origin_h = pic_res.Height
            origin_w = pic_res.Width
            pic_res.Height = pic_height
            pic_res.Width = int((pic_height / origin_h) * origin_w)


def insert_page(pointer, name, tel, id_num, pc):
    name_ = '姓名：' + name
    tel = '联系电话：' + tel
    id_num = '身份证号：' + id_num
    if pc is None:
        pc = '电脑型号：'
    else:
        pc = '电脑型号：' + pc
    pointer.Paragraphs.LineSpacingRule = 4
    pointer.ParagraphFormat.LineSpacing = 21  # 段落行间距
    pointer.TypeText(name_)
    if len(name) == 3:
        pointer.TypeText(four_space)
    elif len(name) == 2:
        pointer.TypeText(five_space)
    pointer.TypeText(tel)
    pointer.TypeText('   ')
    pointer.TypeText(id_num)
    table = doc.Tables.Add(doc.Range(pointer.End, pointer.End), 2, 2)

    pointer.End = pointer.End + 2
    pointer.Paragraphs.LineSpacingRule = 4
    pointer.ParagraphFormat.LineSpacing = 21  # 段落行间距
    table.Cell(1, 1).Range.Text = '车辆信息：'
    table.Cell(1, 2).Range.Text = pc
    pointer.Start = doc.Range().End
    pointer.Paragraphs.LineSpacingRule = 0  # 单倍行距
    doc.Tables.Add(doc.Range(pointer.End, pointer.End), 2, 3)


# 删除某页
def delete_page(pointer):
    result = pointer.GoToNext(1)
    end_index = result.End
    result = pointer.GoToPrevious(1)
    start_index = result.End
    pointer.Start = start_index
    pointer.End = end_index
    if start_index != 0:  # 第一页要少删一次
        pointer.Delete()  # 删除后往下空格一行，再来此回删即可
    pointer.Delete()


def judge_str(origin_str, special_str):
    if special_str in origin_str:
        return True
    return False


if __name__ == '__main__':
    param = normal.get_content()
    tmp_path = _global_dict['root_path']
    root_path = _global_dict['root_path']
    pic_path = _global_dict['pic_path']
    new_pic_path = _global_dict['new_pic_path']
    pic_height = 255
    # 读取文件
    file_index = {'approval_form': -1, 'person_info': -1, 'info_collection': -1}
    word_excel_type = ('.doc', '.docx', '.xls')
    file_list = normal.get_directed_file(tmp_path, word_excel_type)
    # person_info = {'name': 'null', 'tel': 'null', 'id_num': 'null',
    #                'pc': 'null'}
    for i, item in enumerate(file_list):
        if judge_str(item, '审批单'):
            file_index['approval_form'] = i
        elif judge_str(item, '防疫'):
            file_index['person_info'] = i
        elif judge_str(item, '信息统计'):
            file_index['info_collection'] = i
    # 提取人员首字母集合
    collection_path = tmp_path + file_list[file_index['info_collection']]
    app = xw.App(visible=False, add_book=False)
    excel_collection = app.books.open(collection_path)
    collection_sheet = excel_collection.sheets[0]
    collection_rows = collection_sheet.range("a1").expand("down").rows.count
    persons_now = collection_rows - 1
    name_list = collection_sheet.range((2, 1), (collection_rows, 1)).value
    # print(name_list)
    pinyin_list = []
    for item in name_list:
        pinyin_list.append(normal.get_name_initial(item))
    # print(pinyin_list)
    name_dict = {}
    for i in range(2, collection_rows + 1):
        name_dict[pinyin_list[i - 2]] = i
    print('---修改word内容---')
    # 遍历word判断是否在集合中
    word = Dispatch('Word.Application')  # 打开word
    word.Visible = False  # 显示word界面
    doc = word.Documents.Open(tmp_path + file_list[file_index['person_info']])
    # doc = word.Documents.Add()
    styles = doc.Styles  # 样式集合对象 每种类型都含样式
    mainBody = styles(-1)  # 正文样式对象
    mainBody.Font.Name = '等线'  # 正文字体
    mainBody.Font.Size = 12  # 正文字号,小四

    cursor = word.Selection  # 获得光标对象并进行选中
    para_nums = doc.Paragraphs.Count
    # print('para_nums:', para_nums)
    unsolved_pages = word.ActiveDocument.ComputeStatistics(2)  # 获取页码数
    # print('pages:', unsolved_pages)
    # cursor.GoToNext(1)
    four_space = '    '
    five_space = '     '
    name_index = 1
    pc_index = 18
    id_index = 7
    tel_index = 8
    i_index = 0
    if param == 'new':
        for i in range(unsolved_pages):
            # 获取每页第一行
            first_para = doc.Paragraphs[i_index * 16].Range()
            split_first_para = first_para.split()
            name = split_first_para[0][3:]
            name_py = normal.get_name_initial(name)
            if name_py in pinyin_list:
                # 更新电脑信息
                pc_info = collection_sheet.range(name_dict[name_py], pc_index).value
                if pc_info is None:
                    pc_info = '电脑型号：'
                else:
                    pc_info = '电脑型号：' + pc_info
                name_dict.pop(name_py)
                doc.Tables[i_index].Cell(1, 2).Range.Text = pc_info
                cursor.GoToNext(1)
                i_index += 1
            else:
                # 删除页面
                if i == unsolved_pages - 1 or unsolved_pages == 1:
                    cursor.End = doc.Range().End
                    cursor.Delete()
                    cursor.MoveUp()
                    cursor.MoveUp()
                    cursor.Delete()
                    cursor.Delete()
                else:
                    delete_page(cursor)

        # 补充新增人员信息
        table_index = doc.Tables.Count
        if len(name_dict) != 0:
            for item in name_dict:
                name = collection_sheet.range(name_dict[item], name_index).value
                tel = collection_sheet.range(name_dict[item], tel_index).value
                id_num = collection_sheet.range(name_dict[item], id_index).value
                pc = collection_sheet.range(name_dict[item], pc_index).value
                if doc.Range().End != 0:
                    cursor.Start = doc.Range().End
                    # cursor.End = doc.Range().End
                    cursor.InsertBreak()
                insert_page(cursor, name, tel, id_num, pc)
                name_folder = normal.get_name_initial(name)
                name_path = new_pic_path + name_folder + '/'
                insert_pic(doc, table_index, name_path)
                table_index += 1
                break

    # 替换行程码
    print('替换当日行程码')
    for index, item in enumerate(pinyin_list):
        travel_route_pic = pic_path + item + '.jpg'
        doc.Tables[index].Cell(4, 2).Range.Delete()
        pic_res = doc.Tables[index].Cell(4, 2).Range.InlineShapes.AddPicture(travel_route_pic)
        origin_h = pic_res.Height
        origin_w = pic_res.Width
        pic_res.Height = pic_height
        pic_res.Width = int((pic_height / origin_h) * origin_w)
    print('---word内容修改完成---')
    excel_collection.close()
    app.kill()
    file_name = tmp_path + file_list[file_index['person_info']]
    doc.SaveAs(file_name)
    doc.Close()
    word.Quit()
    zip_flag = input('是否打包文件（y/n)\n')
    if zip_flag == 'y':
        os.chdir(tmp_path)
        zip_name = 'ziped_file/报岗信息-' + normal.get_time(1, '-') + '.zip'
        zip = zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED)
        os.chdir(tmp_path)
        for file in file_list:
            zip.write(file)
        zip.close()
        print('打包完成')
